import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/constants.dart';
import '../../core/routes.dart';
import '../viewmodels/game_viewmodel.dart';
import '../widgets/puzzle_board.dart';

/// 游戏界面
class GameScreen extends StatefulWidget {
  final String? imagePath;
  final DifficultyLevel? difficulty;
  
  const GameScreen({
    super.key, // 修复：使用super.key
    this.imagePath,
    this.difficulty,
  });
  
  @override
  State<GameScreen> createState() => _GameScreenState();
}

class _GameScreenState extends State<GameScreen> 
    with TickerProviderStateMixin {
  
  // 动画控制器
  late AnimationController _celebrationController;
  late Animation<double> _celebrationScale;
  late Animation<double> _celebrationRotation;
  
  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _initializeGame();
  }
  
  void _initializeAnimations() {
    _celebrationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );
    
    _celebrationScale = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _celebrationController,
      curve: Curves.elasticOut,
    ));
    
    _celebrationRotation = Tween<double>(
      begin: 0.0,
      end: 0.5,
    ).animate(CurvedAnimation(
      parent: _celebrationController,
      curve: Curves.easeInOut,
    ));
  }
  
  void _initializeGame() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final gameViewModel = Provider.of<GameViewModel>(context, listen: false);
      
      if (widget.imagePath != null && widget.difficulty != null) {
        gameViewModel.initializeGame(
          imagePath: widget.imagePath!,
          difficulty: widget.difficulty!,
        );
      }
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: Consumer<GameViewModel>(
        builder: (context, gameViewModel, child) {
          return Stack(
            children: [
              // 主要游戏内容
              _buildGameContent(gameViewModel),
              
              // 加载遮罩
              if (gameViewModel.isLoading)
                _buildLoadingOverlay(),
              
              // 完成庆祝动画
              if (gameViewModel.currentGame.isCompleted)
                _buildCompletionCelebration(gameViewModel),
            ],
          );
        },
      ),
    );
  }
  
  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: const Text('拼图大师'),
      leading: IconButton(
        icon: const Icon(Icons.arrow_back),
        onPressed: () => _handleBackPressed(),
      ),
      actions: [
        // 暂停/恢复按钮
        Consumer<GameViewModel>(
          builder: (context, gameViewModel, child) {
            if (gameViewModel.currentGame.isPlaying) {
              return IconButton(
                icon: const Icon(Icons.pause),
                onPressed: gameViewModel.pauseGame,
                tooltip: '暂停',
              );
            } else if (gameViewModel.currentGame.isPaused) {
              return IconButton(
                icon: const Icon(Icons.play_arrow),
                onPressed: gameViewModel.resumeGame,
                tooltip: '继续',
              );
            }
            return const SizedBox.shrink();
          },
        ),
        
        // 更多选项
        PopupMenuButton<String>(
          onSelected: _handleMenuSelection,
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'restart',
              child: ListTile(
                leading: Icon(Icons.refresh),
                title: Text('重新开始'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'shuffle',
              child: ListTile(
                leading: Icon(Icons.shuffle),
                title: Text('重新打乱'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'hint',
              child: ListTile(
                leading: Icon(Icons.lightbulb_outline),
                title: Text('提示'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'home',
              child: ListTile(
                leading: Icon(Icons.home),
                title: Text('返回主页'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ],
        ),
      ],
    );
  }
  
  /// 构建游戏内容
  Widget _buildGameContent(GameViewModel gameViewModel) {
    return Column(
      children: [
        // 游戏统计信息
        _buildGameStats(gameViewModel),
        
        // 游戏主要区域
        Expanded(
          child: _buildGameArea(gameViewModel),
        ),
        
        // 控制按钮区域
        _buildControlArea(gameViewModel),
      ],
    );
  }
  
  /// 游戏统计信息
  Widget _buildGameStats(GameViewModel gameViewModel) {
    final theme = Theme.of(context);
    final game = gameViewModel.currentGame;
    
    return Container(
      margin: AppConstants.defaultPadding,
      padding: AppConstants.smallPadding,
      decoration: BoxDecoration(
        color: theme.colorScheme.surface,
        borderRadius: AppConstants.defaultBorderRadius,
        border: Border.all(
          color: theme.colorScheme.outline.withValues(alpha: 0.2), // 修复：使用withValues
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 难度
          _buildStatItem(
            icon: Icons.bar_chart,
            label: '难度',
            value: game.difficulty.displayName,
            color: game.difficulty.color,
          ),
          
          // 进度
          _buildStatItem(
            icon: Icons.pie_chart,
            label: '进度',
            value: '${game.correctlyPlacedCount}/${game.totalPieces}',
            color: AppConstants.successColor,
          ),
          
          // 移动次数
          _buildStatItem(
            icon: Icons.touch_app,
            label: '移动',
            value: '${game.moveCount}',
            color: AppConstants.primaryColor,
          ),
          
          // 用时
          _buildStatItem(
            icon: Icons.timer,
            label: '用时',
            value: gameViewModel.formattedElapsedTime,
            color: AppConstants.warningColor,
          ),
        ],
      ),
    );
  }
  
  Widget _buildStatItem({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    final theme = Theme.of(context);
    
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          icon,
          size: 20,
          color: color,
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: theme.textTheme.bodyMedium?.copyWith(
            fontWeight: FontWeight.w600,
            color: color,
          ),
        ),
        Text(
          label,
          style: theme.textTheme.bodySmall?.copyWith(
            color: theme.colorScheme.onSurface.withValues(alpha: 0.6), // 修复：使用withValues
          ),
        ),
      ],
    );
  }
  
  /// 游戏主要区域
  Widget _buildGameArea(GameViewModel gameViewModel) {
    if (gameViewModel.errorMessage != null) {
      return _buildErrorState(gameViewModel.errorMessage!);
    }
    
    if (gameViewModel.currentGame.pieces.isEmpty) {
      return const Center(
        child: Text('请选择图片开始游戏'),
      );
    }
    
    return PuzzleBoard(
  game: gameViewModel.currentGame,
  onPieceClick: gameViewModel.handlePieceClick,
  onEmptyGridClick: gameViewModel.handleEmptyGridClick,
);

  }
  
  /// 错误状态
  Widget _buildErrorState(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red.shade400,
          ),
          const SizedBox(height: 16),
          Text(
            '游戏出错了',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.red.shade600,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            error,
            style: TextStyle(
              color: Colors.red.shade500,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              final gameViewModel = Provider.of<GameViewModel>(context, listen: false);
              gameViewModel.resetGame();
            },
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }
  
  /// 控制区域
  Widget _buildControlArea(GameViewModel gameViewModel) {
    return Container(
      padding: AppConstants.defaultPadding,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 重新开始
          _buildControlButton(
            icon: Icons.refresh,
            label: '重新开始',
            onPressed: gameViewModel.canReset ? gameViewModel.resetGame : null,
          ),
          
          // 打乱拼图
          _buildControlButton(
            icon: Icons.shuffle,
            label: '打乱',
            onPressed: gameViewModel.currentGame.isPlaying 
                ? gameViewModel.shufflePuzzle 
                : null,
          ),
          
          // 提示
          _buildControlButton(
            icon: Icons.lightbulb_outline,
            label: '提示',
            onPressed: gameViewModel.currentGame.isPlaying 
                ? _showHint 
                : null,
          ),
          
          // 返回主页
          _buildControlButton(
            icon: Icons.home,
            label: '主页',
            onPressed: () => Routes.toHome(context),
          ),
        ],
      ),
    );
  }
  
  Widget _buildControlButton({
    required IconData icon,
    required String label,
    required VoidCallback? onPressed,
  }) {
    final theme = Theme.of(context);
    
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        IconButton(
          icon: Icon(icon),
          onPressed: onPressed,
          iconSize: 28,
          color: onPressed != null 
              ? theme.colorScheme.primary 
              : theme.disabledColor,
        ),
        Text(
          label,
          style: theme.textTheme.bodySmall?.copyWith(
            color: onPressed != null 
                ? theme.colorScheme.onSurface 
                : theme.disabledColor,
          ),
        ),
      ],
    );
  }
  
  /// 加载遮罩
  Widget _buildLoadingOverlay() {
    return Container(
      color: Colors.black.withValues(alpha: 0.5), // 修复：使用withValues
      child: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Colors.white),
            SizedBox(height: 16),
            Text(
              '正在生成拼图...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  /// 完成庆祝动画
  Widget _buildCompletionCelebration(GameViewModel gameViewModel) {
    // 启动庆祝动画
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _celebrationController.forward();
    });
    
    return Container(
      color: Colors.black.withValues(alpha: 0.7), // 修复：使用withValues
      child: Center(
        child: ScaleTransition(
          scale: _celebrationScale,
          child: RotationTransition(
            turns: _celebrationRotation,
            child: Container(
              padding: AppConstants.largePadding,
              margin: AppConstants.largePadding,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: AppConstants.largeBorderRadius,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.3), // 修复：使用withValues
                    blurRadius: 20,
                    offset: const Offset(0, 10),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(
                    Icons.celebration,
                    size: 64,
                    color: AppConstants.successColor,
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    '恭喜完成！',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: AppConstants.successColor,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '用时: ${gameViewModel.formattedElapsedTime}',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                  ),
                  Text(
                    '移动: ${gameViewModel.currentGame.moveCount} 次',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 24),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ElevatedButton(
                        onPressed: gameViewModel.resetGame,
                        child: const Text('再来一局'),
                      ),
                      const SizedBox(width: 12),
                      OutlinedButton(
                        onPressed: () => Routes.toHome(context),
                        child: const Text('返回主页'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
  
  /// 处理返回按钮
  void _handleBackPressed() {
    final gameViewModel = Provider.of<GameViewModel>(context, listen: false);
    
    if (gameViewModel.currentGame.isPlaying) {
      // 暂停游戏并显示确认对话框
      gameViewModel.pauseGame();
      _showExitConfirmDialog();
    } else {
      Routes.toHome(context);
    }
  }
  
  /// 显示退出确认对话框
  void _showExitConfirmDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认退出'),
        content: const Text('当前游戏进度将会丢失，确定要退出吗？'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              final gameViewModel = Provider.of<GameViewModel>(context, listen: false);
              gameViewModel.resumeGame();
            },
            child: const Text('继续游戏'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              Routes.toHome(context);
            },
            child: const Text('退出'),
          ),
        ],
      ),
    );
  }
  
  /// 处理菜单选择
  void _handleMenuSelection(String value) {
    final gameViewModel = Provider.of<GameViewModel>(context, listen: false);
    
    switch (value) {
      case 'restart':
        gameViewModel.resetGame();
        break;
      case 'shuffle':
        gameViewModel.shufflePuzzle();
        break;
      case 'hint':
        _showHint();
        break;
      case 'home':
        Routes.toHome(context);
        break;
    }
  }
  
  /// 显示提示
  void _showHint() {
    final gameViewModel = Provider.of<GameViewModel>(context, listen: false);
    final hint = gameViewModel.getHint();
    
    if (hint != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('提示：尝试放置第${hint.id + 1}号拼图块'),
          action: SnackBarAction(
            label: '知道了',
            onPressed: () {},
          ),
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('当前没有可用提示'),
        ),
      );
    }
  }
  
  @override
  void dispose() {
    _celebrationController.dispose();
    super.dispose();
  }
}
